package com.sapp.imagecolorization.image_settings

import android.app.Activity
import android.content.Intent
import android.provider.MediaStore
import android.widget.ImageView
import android.widget.ProgressBar
import com.sapp.imagecolorization.retrofit.RestApiService
import com.sapp.imagecolorization.retrofit.imageUrlToDownload
import com.sapp.imagecolorization.utils.RuntimePermission
import com.squareup.picasso.Picasso
import me.relex.photodraweeview.PhotoDraweeView
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.util.*


class ImageSettings {
    private val permission = RuntimePermission()

    fun loadStorageImage(
        context: Activity,
        restApiService: RestApiService,
        imagePath: String,
        imageView: PhotoDraweeView,
        progressBar: ProgressBar
    ) {
        val file = File(imagePath)
        val requestFile: RequestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), file)

        // MultipartBody.Part is used to send also the actual file name
        val body =
            MultipartBody.Part.createFormData("image", file.name, requestFile)

        restApiService.loadStorageImage(context, body, imageView, progressBar)
    }

    fun selectPhoto(
        context: Activity,
        permissions: Array<out String>,
        requestPermissionId: Int,
        selectPhotoId: Int
    ) {
        permission.checkPermission(context, permissions, requestPermissionId) {
            val i = Intent(
                Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            )
            context.startActivityForResult(i, selectPhotoId)

        }
    }

    fun imageDownload(context: Activity, url: String): String {
        val fileName = UUID.randomUUID().toString() + ".jpg"
        Picasso.get()
            .load(url)
            .into(SaveImageHelper(context, context.contentResolver, fileName, "Colorized Image"))

        return fileName
    }

    fun shareImage(context: Activity) {
        val shareIntent = Intent(Intent.ACTION_SEND)
        shareIntent.type = "text/plain"
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Colorized image")
        val shareMessage = imageUrlToDownload
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareMessage)
        context.startActivity(Intent.createChooser(shareIntent, "choose one"))
    }

}